package com.lxhll.personnel.controller.role;


import com.baomidou.mybatisplus.extension.api.ApiController;
import com.lxhll.personnel.core.ResponseData;
import com.lxhll.personnel.entity.Employee;
import com.lxhll.personnel.entity.Role;
import com.lxhll.personnel.service.EmployeeRoleService;
import com.lxhll.personnel.service.EmployeeService;
import com.lxhll.personnel.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Role)表控制层
 *
 * @author makejava
 * @since 2021-07-22 14:37:22
 */
@RestController
@RequestMapping("/role")
public class RoleController extends ApiController {
    // 注入
    @Autowired
    private RoleService roleService;

    @Autowired
    private EmployeeRoleService employeeRoleService;

    @Autowired
    private EmployeeService employeeService;


    @PostMapping("/list")
    public ResponseData list() {
        List<Role> list = roleService.list();
        return ResponseData.ok(list);
    }



    @GetMapping("/info/{id}")
    public ResponseData info(@PathVariable("id") Long id) {
        Role entity = roleService.getById(id);
        return ResponseData.ok(entity);
    }


    @PostMapping("/save")
    public ResponseData save(@Validated @RequestBody Role entity) {
        roleService.save(entity);
        return ResponseData.ok();
    }


    @PostMapping("/update")
    public ResponseData update(@Validated @RequestBody Role entity) {
        roleService.updateById(entity);
        return ResponseData.ok();
    }



    @PostMapping("/delete")
    public ResponseData delete(@RequestBody Integer[] ids) {


        roleService.deleteUserAndRole(ids);


        return ResponseData.ok();
    }

    /**
     * 分配角色
     * @param id
     * @return
     */
    @GetMapping("/transfer/{id}")
    public ResponseData transfer (@PathVariable("id") Integer id) {

        //根据角色id查询分配给了哪些用户
        List<Employee> yesdis=employeeRoleService.getEmployeeByRoleId(id);

        //查询所有用户
        List<Employee> all=employeeService.list();


        //返回多个结果，使用map
        Map<String,Object> m= new HashMap<>();
        m.put("yesdis", yesdis);
        m.put("all", all);
        return ResponseData.ok(m);
    }


    /**
     * 保存分配
     * @param ids
     * @return
     */
    @PostMapping("/save_transfer")
    public ResponseData saveTransfer(@RequestBody Integer[] ids) {

        System.out.println(ids);

        //用户id数组
        Integer[] eids= Arrays.copyOf(ids,ids.length-1);
        //角色id
        Integer rid=ids[ids.length-1];


        //关系保存到sys_user_role
        roleService.saveTransfer(rid, eids);

        return ResponseData.ok();
    }
}
